//
//  LoginController.swift
//  YOKO
//
//  Created by 鲁浩 on 16/5/18.
//  Copyright © 2016年 15Tec. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON
import SnapKit

class LoginViewController: UIViewController, UITextFieldDelegate {

	// static let URL : String = ""

	@IBOutlet weak var phoneNumberText: UITextField!

	@IBOutlet weak var verificationCodeText: UITextField!

	@IBOutlet weak var getVerifycodeButton: UIButton!

	@IBOutlet weak var withoutLoginView: UIView!

	var countdownTimer: NSTimer?

	var remainingSeconds: Int = 0 {
		willSet {
			getVerifycodeButton.setTitle("\(newValue)秒后可重发", forState: .Disabled)

			if newValue <= 0 {
				getVerifycodeButton.setTitle("获取验证码", forState: .Normal)
				isCounting = false
			}
		}
	}

	var isCounting = false {
		willSet {
			if newValue {
				countdownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(LoginViewController.updateTime(_:)), userInfo: nil, repeats: true)

				remainingSeconds = 60

			} else {
				countdownTimer?.invalidate()
				countdownTimer = nil

			}

			getVerifycodeButton.enabled = !newValue
		}
	}

	func updateTime(timer: NSTimer) {
		remainingSeconds -= 1
	}

	var userDefault = NSUserDefaults.standardUserDefaults()

	override func viewDidLoad() {

		// // 清空本地数据库
		// let database = YOKODatabase()
		// database.calendarEntryController.deleteAll()
		// database.eventController.deleteAll()
		//
		// // 清掉user_id
		// userDefault.removeObjectForKey("user_id")

		// 进到这里说明userDefault中肯定没有user_id这个字段=nil

		phoneNumberText.delegate = self

		// if userDefault.stringForKey("user_id") != nil && userDefault.stringForKey("user_id") != "anonymous"  {
		//// showAlertWithMsg("已登录用:" + userDefult.stringForKey("user_nickname")!)
		// //已登录用户跳转monthView
		// didEndPullDatabase()
		//
		// }
		getVerifycodeButton.layer.masksToBounds = true
		getVerifycodeButton.layer.borderWidth = 0.4
        
        //添加一个取消按钮在上方
        let cancelButton = UIButton(type: .Custom)
        cancelButton.setImage(UIImage(named: "ic_close_black"), forState: .Normal)
        cancelButton.contentMode = .ScaleAspectFit
        //cancelButton.backgroundColor = UIColor.yellowColor()
        cancelButton.addTarget(self, action: #selector(LoginViewController.cancelButtonHandler), forControlEvents: .TouchUpInside)
        view.addSubview(cancelButton)
        cancelButton.snp_makeConstraints {
            make in
            make.top.equalTo(20.0)
            make.left.equalTo(10.0)
            make.height.equalTo(25.0)
            make.width.equalTo(25.0)
        }

		view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(LoginViewController.handleTap(_:))))
        let swipeLeaveGesture = UISwipeGestureRecognizer(target: self, action: #selector(LoginViewController.swipeGestureHandler))
        swipeLeaveGesture.direction = .Right
        view.addGestureRecognizer(swipeLeaveGesture)
//		NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LogInViewController.didEndPullDatabase), name: "DatabaseFinishPull", object: nil)
//		withoutLoginView.hidden = true

	}
//
//	dynamic func didEndPullDatabase() {
//
//		let database = YOKODatabase()
//
//		if let defaultCalendar = database.calendarEntryController.findDefaultCalendar() {
//			if userDefault.stringForKey("currentCalendarId") == nil {
//
//				userDefault.setObject(defaultCalendar.calendarId, forKey: "currentCalendarId")
//
//			}
//			NSNotificationCenter.defaultCenter().removeObserver(self)
//			self.performSegueWithIdentifier("login", sender: self)
//		} else {
//			print("这是一个全新的用户，没有default calendar呢")
//			// 添加默认日历本
//			let calendarEntry = CalendarEntry()
//			calendarEntry.primary.value = true
//			calendarEntry.summary = "默认日历"
//			calendarEntry.color = "blue"
//			database.calendarEntryController.add(calendarEntry)
//
//			// 添加Deadline日历本
//			let deadlineCalendar = CalendarEntry()
//			deadlineCalendar.primary.value = false
//			deadlineCalendar.summary = "Deadline"
//			deadlineCalendar.color = "red"
//			database.calendarEntryController.add(deadlineCalendar)
//
//			// 对于本地数据库中一个calendar都没有的用户肯定是新用户，因此userdedefaults的这个字段肯定没有设置
//			userDefault.setObject(database.calendarEntryController.findDefaultCalendar().calendarId, forKey: "currentCalendarId")
//			NSNotificationCenter.defaultCenter().removeObserver(self)
//			self.performSegueWithIdentifier("login", sender: self)
//
//		}
//
//	}
//
	@IBAction func getVerifyCode(sender: UIButton) {

		// 手机号码验证？
		if (!isTelNumber(phoneNumberText.text!)) {
			showAlertWithMsg("请输入正确手机号码")
		} else {
			// let timestamp = "\(Int(NSDate().timeIntervalSince1970 * 1000))"
			// print(timestamp)
			// let session_key = (timestamp + "yoko").md5()

			// Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
			// .responseJSON { response in
			// print("request: \(response.request)") // original URL request print(response.response) // URL response
			// print("data: \(response.data)") // server data
			// print("result: \(response.result)") // result of response serialization
			// }
			// 倒计时按钮开始倒计时
			isCounting = true
            ApiLogin().requestConfirmCode(phoneNumberText.text!) {
                successOrNil, message in
                
                if let success = successOrNil {
                    if success == false {
                        print("\(#function) --> request confirm code failed: \(message!)")
                        dispatch_async(dispatch_get_main_queue()) {
                            () -> Void in
                            self.showAlertWithMsg("获取验证码失败: \(message!)")
                        }
                    }
                }
            }

//			NetworkUtil.TollerantAlamofire.request(.POST, "https://\(GlobalVariables.serverIP)/sms/registercode/send", parameters: ["phone": phoneNumberText.text!], encoding: .JSON).responseJSON { response in
//				switch response.result {
//				case .Success:
//					if let value = response.result.value {
//						let json = JSON(value)
//						print("\(json)")
//
//					} else {
//						self.showAlertWithMsg("服务器异常，请稍后再试！")
//					}
//
//				case .Failure(let error):
//
//					print(error)
//				}
//			}

		}
	}

	@IBAction func phoneNoLogin(sender: UIButton) {
//		NetworkUtil.TollerantAlamofire.request(.GET, "https://\(GlobalVariables.serverIP)/sms/token?" + "phone=" + phoneNumberText.text! + "&code=" + verificationCodeText.text!, encoding: .JSON).responseJSON { response in
//			switch response.result {
//			case .Success:
//				if let value = response.result.value {
//					let json = JSON(value)
//					// print("\(json)")
//					if json["result"] {
//						let user_id = "\(json["data"]["user_id"])"
//						let access_token = "\(json["data"]["access_token"])"
//						// print("user_id==" + user_id)
//						// print("access_token==" + access_token)
//
//						NSUserDefaults.resetStandardUserDefaults()
//
//						self.userDefault.setObject(user_id, forKey: "user_id")
//						self.userDefault.setObject(access_token, forKey: "access_token")
//						// user_nickname字段就是电话号码
//						self.userDefault.setObject(self.phoneNumberText.text!, forKey: "user_nickname")
//						// self.showAlertWithMsg("登录成功 :" + self.phoneNumberText.text!)
//						// 跳转到monthTableView
//						let database = YOKODatabase()
//						database.pullToSyncWithServer()
//					} else {
//						self.showAlertWithMsg("\([json["msg"]])")
//					}
//				} else {
//					self.showAlertWithMsg("服务器异常，请稍后再试！")
//				}
//
//			case .Failure(let error):
//
//				print(error)
//			}
//		}
        if isTelNumber(phoneNumberText.text!) == false {
            self.showAlertWithMsg("手机号无效")
            return
        }
        else if verificationCodeText.text == "" {
            self.showAlertWithMsg("验证码不能为空")
            return
        }
        
        ApiLogin().verifyPhoneAndConfirmCode(phoneNumberText.text!, confirmCode: verificationCodeText.text!) {
            successOrNil, message in
            if let success = successOrNil {
                if success {
                    self.dismissViewControllerAnimated(true, completion: nil)
                }
                else {
                    dispatch_async(dispatch_get_main_queue()) {
                        self.showAlertWithMsg("登录失败")
                    }
                }
            }
        }
	}

	// mark textfieldDelegate
	func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

		let text: NSMutableString = textField.text!.mutableCopy() as! NSMutableString
		text.replaceCharactersInRange(range, withString: string)

		return text.length <= 11
	}

	func showAlertWithMsg(msg: String) {

		let alertView = UIAlertView()
		alertView.title = "温馨提示"
		alertView.message = msg
		alertView.addButtonWithTitle("确定")
		alertView.delegate = self;
		alertView.show()
	}

	func handleTap(sender: UITapGestureRecognizer) {
		if sender.state == .Ended {
			phoneNumberText.resignFirstResponder()
			verificationCodeText.resignFirstResponder()
		}
		sender.cancelsTouchesInView = false
	}

	func isTelNumber(num: NSString) -> Bool
	{
		let mobile = "^1(3[0-9]|5[0-35-9]|8[025-9]|7[0-9])\\d{8}$"
		let CM = "^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$"
		let CU = "^1(3[0-2]|5[256]|8[56]|76)\\d{8}$"
		let CT = "^1((33|53|8[09]|77)[0-9]|349)\\d{7}$"
		let regextestmobile = NSPredicate(format: "SELF MATCHES %@", mobile)
		let regextestcm = NSPredicate(format: "SELF MATCHES %@", CM)
		let regextestcu = NSPredicate(format: "SELF MATCHES %@", CU)
		let regextestct = NSPredicate(format: "SELF MATCHES %@", CT)
		if ((regextestmobile.evaluateWithObject(num) == true)
			|| (regextestcm.evaluateWithObject(num) == true)
			|| (regextestct.evaluateWithObject(num) == true)
			|| (regextestcu.evaluateWithObject(num) == true))
		{
			return true
		}
		else
		{
			return false
		}
	}
    
    func swipeGestureHandler() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func cancelButtonHandler() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 添加到Util里去？
//    func md5(string string: String) -> String {
//        var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
//        if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
//            CC_MD5(data.bytes, CC_LONG(data.length), &digest)
//        }
//        var digestHex = ""
//        for index in 0..<Int(CC_MD5_DIGEST_LENGTH) {
//            digestHex += String(format: "%02x", digest[index])
//        }
//        return digestHex
//    }
}